﻿using UnityEditor;
using UnityEngine;


namespace RStudio.Command.Editor
{
    /// <summary>
    /// 
    /// </summary>
    public class CommandUtil
    {
        /// <summary>
        /// 打开|命令脚本
        /// </summary>
        /// <param name="command">命令类</param>
        public static void OpenCommandScript(ICommand command)
        {
            // 查找对应的脚本文件
            string[] guids = AssetDatabase.FindAssets($"t:Script {command.Name}Command");

            if (guids.Length == 0)
            {
                // 尝试搜索不带Command后缀的
                guids = AssetDatabase.FindAssets($"t:Script {command.Name}");
            }

            if (guids.Length > 0)
            {
                string path = AssetDatabase.GUIDToAssetPath(guids[0]);
                var script = AssetDatabase.LoadAssetAtPath<MonoScript>(path);
                AssetDatabase.OpenAsset(script);
            }
            else
            {
                EditorUtility.DisplayDialog("提示", $"未找到命令 {command.Name} 对应的脚本文件", "确定");
            }
        }

        /// <summary>
        /// 拷贝|命令模板
        /// </summary>
        /// <param name="command"></param>
        public static void CopyCommandTemplate(ICommand command)
        {
            string template = $@"// 基于 {command.Name} 命令的模板
public class {command.Name}TemplateCommand : ICommand
{{
    public string Name => ""{command.Name}_template"";
    public string Description => ""基于 {command.Name} 的模板命令"";
    public CommandPermissionLevel RequiredPermission => CommandPermissionLevel.Normal;
    public string Usage => ""/{command.Name}_template [参数]"";
    
    public string[] ParamArray {{ get; set; }} = System.Array.Empty<string>();

    public bool IsValid(string[] args, out string errorMessage)
    {{
        // 参数验证逻辑
        errorMessage = """";
        return true;
    }}

    public bool Execute(string[] args)
    {{
        if (!IsValid(args, out string errorMessage))
        {{
            Debug.LogError($""参数错误: {{errorMessage}}"");
            return false;
        }}
        
        // 命令执行逻辑
        Debug.Log($""执行模板命令: {{Name}}"");
        return true;
    }}
}}";

            GUIUtility.systemCopyBuffer = template;
            EditorUtility.DisplayDialog("成功", "命令模板已复制到剪贴板", "确定");
        }

    }
}
